package com.ruoyi.jt808.util;

import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Bytes2Util {

    public static String bytesToHex(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }

    public static byte[] hexToBytes(String hex) {
        if (hex == null || hex.isEmpty()) {
            return new byte[0];
        }

        int len = hex.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            try {
                data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                        + Character.digit(hex.charAt(i+1), 16));
            } catch (Exception e) {
                log.error("Hex to bytes conversion error: {}", e.getMessage());
                return new byte[0];
            }
        }
        return data;
    }

    public static byte[] readBytes(ByteBuf buf, int length) {
        if (buf == null || length <= 0) {
            return new byte[0];
        }

        byte[] bytes = new byte[length];
        buf.readBytes(bytes);
        return bytes;
    }
}
